<?php
// +----------------------------------------------------------------------
// | zlserver [ 小程序 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------
namespace app\job\import;

use think\exception\ErrorException;
use think\facade\Validate;
use think\queue\Job;
use app\common\model\StudentInfo as StudentInfoModel; 
use app\common\model\User as UserModel; 
use app\common\model\StudentInfoImport as StudentInfoImportModel;
use app\common\model\CwStructCache as CwStructCacheModel;
use app\common\model\ManageUserRoleRel as ManageUserRoleRelModel;


use app\common\model\Ietask;
use think\facade\Log;

class Student
{
    protected $rule = [
        'xh' => 'require|max:40',
        'xm' => 'require|max:40',
        'truename' => 'require|max:40',
        'dir' => 'require|in:就业,升学,创业', 
    ];
    protected $msg = [
        'xh.require' => '学号必填',
        'xh.max' => '学号最长40个字符',
        'xm.require' => '姓名必填',
        'xm.max' => '姓名最长40个字符',
        'truename.require' => '辅导员姓名必填',
        'truename.max' => '辅导员姓名最长40个字符',
        'dir.in' => '方向类型错误:请参考模板性别类型介绍，或咨询系统管理员',
        'dir.require' => '方向必填'
    ];

    // 数据校验
    public function check($fileId, $filePath)
    {
        $re = [
            'count' => 0,
            'code' => 0,
            'msg' => ''
        ];

        $studentInfoModel = new StudentInfoModel();
        $userModel = new UserModel();
        $data = [];
        $errorData = [];
        try {
            $resXls=import_excel($filePath);  

            if ($resXls['status']) {
                // 清理导入提示
                unset($resXls['data'][0]);
                // 取表头
                $header = $resXls['data'][1];
                unset($resXls['data'][1]);
                $title = $studentInfoModel->csvHeader();
                $fields = [];

                // 遍历表头
                $last_index = 0;
                foreach ($title as $key => $val) {
                    // 从导入的数据表中查找字段位置
                    $index = array_search($val['desc'], $header);
                    if ($index !== false) {
                        $fields[] = [
                            'index' => $index,
                            'value' => $val['id']
                        ];
                    }
                    $last_index = $index;
                }
 
                if(count($fields) != 5) { 
                    $re['msg']  = '文件格式错误！请先下载导入模板，按模板要求准备导入数据后再次导入！';
                    $re['code']  = -1;
                    return $re;
                } else {

                    // 数据填充
                    $iData = [];
                    if ($fields) {
                        $i = 0;
                        foreach ($resXls['data'] as $key => $val) {
                            foreach ($fields as $fkey => $fval) {
                                $iData[$i][$fval['value']] = $val[$fval['index']];
                                if(is_object($iData[$i][$fval['value']])) {
                                    $iData[$i][$fval['value']] = $iData[$i][$fval['value']]->__toString();
                                }
                            }
                            $i++;
                        }
                    }
    
                    // 增加描述字段
                    $fields[] = [
                        'index' => $last_index + 1,
                        'value' => 'desc'
                    ];
                    
                    $count = count($iData);
                    $errCount = 0;
     
                    // 学号是否存在
                    $xhList = $studentInfoModel->getXhList(); 
                    // 学号姓名是否存在
                    $xhNameList = $studentInfoModel->getXhNameList(); 
                    // 是否已提交未领取
                    $unDrawList = $studentInfoModel->getXhTeacherUnDrawList(); 
                    // 提取所有教师信息
                    $mobileList = $userModel->getMobileNameList(); 

                    $tmp_arr = array(); 
                    // 数据预处理 
                    foreach ($iData as $key => $val) {
                        $errFind = false;
                        //校验数据
                        $validate = new \think\Validate($this->rule, $this->msg);
                        $validate->batch(true);

                        // 数据预处理
                        $time = time();
                        $student['xh'] = trim($val['xh']);
                        $student['xm'] = trim($val['xm']);
                        $student['dir'] = trim($val['dir']);
                        $student['mobile'] = trim($val['mobile']);
                        $student['truename'] = trim($val['truename']);
                        $student['desc'] = '';
                        $student['error'] = 0;
 
                        if (!$validate->check($student)) {
                            $student['error'] = 1;
                            $errCount = $errCount + 1;
                            $errFind = true;

                            $index = 0;
                            foreach ($validate->getError() as $errKey => $value) {
                                if($index == 0) {
                                    $student['desc']  = $student['desc'] . $value;
                                } else {
                                    $student['desc']  = $student['desc'] . ';' . $value;
                                }
                                $index++;
                            }  
                        }

                        // 判断学号是否存在
                        if (!in_array($student['xh'], $xhList)) {
                            $student['error'] = 1;

                            if(strpos($student['desc'], '学号') === false) { 
                                if($errFind) {
                                    $student['desc'] =  $student['desc'] . ';' . $student['xh'] . '学号不存在';
                                } else {
                                    $errCount = $errCount + 1;
                                    $errFind = true;
                                    $student['desc'] =  $student['xh'] . '学号不存在';
                                }
                            }
                        } else {
                            // 学号姓名是否一致
                            if (!in_array($student['xh'].$student['xm'], $xhNameList)) {
                                $student['error'] = 1;

                                if($errFind) {
                                    $student['desc'] =  $student['desc'] . ';' . $student['xh'] . '学号姓名不一致！';
                                } else {
                                    $errCount = $errCount + 1;
                                    $errFind = true;
                                    $student['desc'] =  $student['xh'] . '学号姓名不一致！';
                                }
                            }
                        }

                        if (in_array($student['xh'], $unDrawList)) {
                            $student['error'] = 1;

                            if($errFind) {
                                $student['desc'] =  $student['desc'] . ';' . $student['xh'] . '存在申请未领取记录！';
                            } else {
                                $errCount = $errCount + 1;
                                $errFind = true;
                                $student['desc'] =  $student['xh'] . '存在申请未领取记录！';
                            }
                        }
                        
                        // 手机号检测 /^1[34578]{1}\d{9}$/
                        if(!preg_match("/^1[3|4|5|6|7|8|9][0-9]\d{8}$/", $student['mobile'])) {
                            $student['error'] = 1;
                            if(strpos($student['desc'], '手机号码') === false) { 
                                if($errFind) {
                                    $student['desc'] =  $student['desc'] . ';' . '请输入一个合法的手机号码';
                                } else {
                                    $errCount = $errCount + 1;
                                    $errFind = true;
                                    $student['desc'] =  $student['desc'] . '请输入一个合法的手机号码';
                                }
                            }
                        }

                        if (array_key_exists(trim($student['mobile']), $mobileList)) {
                            if($student['truename'] != $mobileList[$student['mobile']]){
                                $student['error'] = 1;
                                if(strpos($student['desc'], '手机号码') === false) { 
                                    if($errFind) {
                                        $student['desc'] =  $student['desc'] . ';' . '手机号与辅导员姓名不符';
                                    } else {
                                        $errCount = $errCount + 1;
                                        $errFind = true;
                                        $student['desc'] =  $student['desc'] . '手机号与辅导员姓名不符';
                                    }
                                }
                            }
                        } else {
                            $student['error'] = 1;
                            if($errFind) {
                                $student['desc'] = $student['desc'] . ';' . '辅导员手机不存在'; 
                            } else {
                                $errCount = $errCount + 1;
                                $errFind = true;
                                $student['desc'] = $student['desc'] . '辅导员手机不存在'; 
                            }
                        }

                        // 自身检测
                        if (in_array($student['xh'], $tmp_arr)) { //搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
                            $student['error'] = 1;
                            if($errFind) {
                                $student['desc'] = $student['desc'] . ';' . '导入数据中学号重复'; 
                            } else {
                                $errCount = $errCount + 1;
                                $errFind = true;
                                $student['desc'] = $student['desc'] . '导入数据中学号重复'; 
                            }
                        } else {
                            if($student['xh'] != '') {
                                $tmp_arr[] = $student['xh'];
                            }
                        }

                        if ($student['error'] == 1) {
                            $errorData[$errCount - 1] = $student;
                        }
    
                        $data[$key] = $student;
                        unset($student);
                    }
                } 
            } else {
                $re['msg']  = $resXls['msg'];
                $re['code']  = -1;
                return $re;
            }
        } catch (Exception $e) {
            $re['msg']  = $e->getMessage();
            $re['code']  = -1;
            return $re;
        }

        $re['count'] = $count;
        $re['errCount'] = $errCount;
        $re['data'] = json_encode($data);
        $re['fileId'] = $fileId;
        $re['filePath'] = $filePath;
        $re['errData'] = json_encode($errorData);
        return $re;
    }

    //执行导入任务
    public function exec(Job $job, $params)
    { 
        $ietaskModle = new Ietask();

        $ietaskInfo = $ietaskModle->where(['id' => $params['task_id']])->find();

        $studentInfoModel = new StudentInfoModel();
        $userModel = new UserModel();
        $studentInfoImportModel = new StudentInfoImportModel();
        $userRoleModel = new ManageUserRoleRelModel(); 
        $message = [];
        $count = 0;         // 记录总数
        $progress = 0;
        try {
            $file = json_decode($params['params'], true);
            $resXls=import_excel($file['file_path']); 
            $count = count($resXls['data'])-2;

            if ($resXls['status']) {
                // 清理导入提示
                unset($resXls['data'][0]);
                // 取表头
                $header = $resXls['data'][1];
                unset($resXls['data'][1]);
                $title = $studentInfoModel->csvHeader(); 
                 
                $fields = []; 
                foreach ($title as $key => $val) {
                    $index = array_search($val['desc'], $header);
                    if ($index >= 0) {
                        $fields[] = [
                            'index' => $index,
                            'value' => $val['id']
                        ];
                    }
                }

                // 提取所有学生信息
                $iData = [];
                if ($fields) {
                    $i = 0;
                    foreach ($resXls['data'] as $key => $val) {
                        foreach ($fields as $fkey => $fval) {
                            $iData[$i][$fval['value']] = $val[$fval['index']];
                            if(is_object($iData[$i][$fval['value']])) {
                                $iData[$i][$fval['value']] = $iData[$i][$fval['value']]->__toString();
                            }
                        }
                        $i++;
                    }
                }
 
                // // 提取所有教师信息
                // $mobileList = $userModel->getMobileList(); 
                // $tData = [];
                // $tData = [];   // 用于判断是否本地导入内容
                // foreach ($iData as $key => $val) {
                //     if (!in_array($val['mobile'], $mobileList)) {
                //         if (!array_key_exists(trim($val['mobile']), $tData)) {
                //             // 获取用户所在的部门
                //             $cwStructCacheModel = new CwStructCacheModel();
                //             $studentInfo = $cwStructCacheModel->field('a.bmdm')
                //                 ->alias('a')
                //                 ->join('zlzhsf.pxsdm b', 'a.bjdm = b.bjdm')
                //                 ->where(['b.xh'=>$val['xh']])
                //                 ->find();
                            
                //             $bmdm = 1;
                //             if($studentInfo) {
                //                 $bmdm = $studentInfo['bmdm'];
                //             }

                //             $tData[trim($val['mobile'])] = [
                //                 'mobile' => trim($val['mobile']),
                //                 'truename' => trim($val['truename']),
                //                 'dept' => $bmdm
                //             ];
                //         }
                //     }
                // }

                // $time = time();
                // $defaultPwd = md5(md5('123123') . $time);
 
                // unset($user_comment);
                // $user_comment = []; 
                // $username_array = [];   // 用于判断是否本地导入内容
                // foreach ($tData as $key => $val) { 
                //     $sex = $userModel::SEX_BOY;
                //     $status = $userModel::STATUS_NORMAL; 

                //     $user_comment[] = [
                //         'username'    => trim($val['mobile']),
                //         'truename'  => trim($val['truename']),
                //         'deptId'  => trim($val['dept']),
                //         'positionId'  => 1,
                //         'password' => $defaultPwd,
                //         'mobile' => trim($val['mobile']),
                //         'sex'    => $sex,
                //         'status'  => $status,
                //         'ctime'    => $time,
                //         'utime'    => $time,
                //     ];
     
                //     if (!in_array(trim($val['mobile']), $username_array)) {
                //         $username_array[] = trim($val['mobile']);
                //     }

                //     // 每隔100条数据更新一次数据处理进度
                //     $progress++; 
                //     if($progress %100==0) {
                //         // 批量插入数据
                //         $userModel->startTrans(); 
                //         $num = $userModel->insertAll($user_comment);
                //         if($num != 100) {
                //             $userModel->rollback();
                //             Log::record($user_comment . '用户数据保存失败');
                //         } else {                        
                //             $userModel->commit();
                //         }

                //         // 清理环境
                //         unset($user_comment);
                //         $user_comment = [];
                //     }
                // }

                // // 批量插入数据
                // $userModel->startTrans(); 
                // $num = $userModel->insertAll($user_comment);               
                // $userModel->commit(); 
   
                // // 批量更新角色信息
                // $userRoleModel = new ManageUserRoleRelModel();
                // $userInfoList = $userModel->getIDAndUsernameList(); 
                // //角色信息
                // $jobProgress = 0;
                // unset($user_job_comment);
                // $user_job_comment = [];
                // foreach ($userInfoList as $jobKey => $jobVal) {
                //     // 首先判断是否是本次导入的数据
                //     if(in_array($jobVal['username'], $username_array)) { 
                //         $user_job_comment[] = [
                //             'manage_id'    => $jobVal['id'],
                //             'role_id'  => 5
                //         ];

                //         // 每隔100条数据更新一次数据处理进度
                //         $jobProgress++; 
                //         if($jobProgress %100==0) {
                //             // 批量插入数据
                //             $userRoleModel->startTrans(); 
                //             $num = $userRoleModel->insertAll($user_job_comment);
                //             if($num != 100) {
                //                 $userRoleModel->rollback();
                //                 Log::record($user_job_comment . '用户数据保存失败');
                //             } else {                        
                //                 $userRoleModel->commit();
                //             }
    
                //             // 清理环境
                //             unset($user_job_comment);
                //             $user_job_comment = [];
                //         }  
                //     } 
                // }
   
                // // 批量插入数据
                // $userRoleModel->startTrans(); 
                // $num = $userRoleModel->insertAll($user_job_comment);               
                // $userRoleModel->commit(); 

                // 清空临时表
                $studentInfoImportModel->where(['manage_id' => $ietaskInfo['manage_id']])->delete();

                // 学生信息写入临时表
                unset($student_comment);
                $student_comment = []; 
                foreach ($iData as $key => $val) { 
                    $sex = $userModel::SEX_BOY;
                    $status = $userModel::STATUS_DISABLE; 

                    $student_comment[] = [
                        'xh'        => trim($val['xh']),
                        'xm'        => trim($val['xm']),
                        'dir'       => trim($val['dir']),
                        'mobile'    => trim($val['mobile']),
                        'truename'  => trim($val['truename']),
                        'manage_id' => trim($ietaskInfo['manage_id']),
                    ];
     
                    // 每隔100条数据更新一次数据处理进度
                    $progress++; 
                    if($progress %100==0) {
                        // 批量插入数据
                        $studentInfoImportModel->startTrans(); 
                        $num = $studentInfoImportModel->insertAll($student_comment);
                        if($num != 100) {
                            $studentInfoImportModel->rollback();
                            Log::record($student_comment . '用户数据保存失败');
                        } else {                        
                            $studentInfoImportModel->commit();
                        }

                        // 清理环境
                        unset($student_comment);
                        $student_comment = [];
                    }
                }

                // 批量插入数据
                $studentInfoImportModel->startTrans(); 
                $num = $studentInfoImportModel->insertAll($student_comment);               
                $studentInfoImportModel->commit(); 

                // 执行存储过程批量更新学生信息
                $studentInfoImportModel->query("call programUpdateStudentInfo('".$ietaskInfo['manage_id']."');");
        
                // 清空临时表
                $studentInfoImportModel->where(['manage_id' => $ietaskInfo['manage_id']])->delete();
                
                $uData['status'] = $ietaskModle::IMPORT_SUCCESS_STATUS;
                $uData['message'] = '导入成功';
                if ($message) {
                    $uData['message'] .= json_encode($message);
                }

                $uData['count'] = $count;
                $ietaskModle->update($uData, ['id' => $params['task_id']]);
            } else {
                $uData['status'] = $ietaskModle::IMPORT_FAIL_STATUS;
                $uData['message'] = $resXls['msg'];
                $uData['utime'] = time();
                $ietaskModle->update($uData, ['id' => $params['task_id']]);
            }
        } catch (Exception $e) {
            $message[] = $e->getMessage();
        }
        if ($job->attempts() > 3) {
            $uData['status'] = $ietaskModle::IMPORT_FAIL_STATUS;
            $uData['message'] = '导入执行失败';
            $uData['utime'] = time();
            $ietaskModle->update($uData, ['id' => $params['task_id']]);
            $job->delete();
        }
    }

    public function failed($data)
    {

        // ...任务达到最大重试次数后，失败了
    }
}
